package com.kotlin.dongdong.framework.http

import android.util.Log
import com.google.gson.GsonBuilder
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import com.kotlin.dongdong.framework.BuildConfig
import com.kotlin.dongdong.framework.http.apiservice.UserService
import com.kotlin.dongdong.framework.http.cret.MyX509Certificate
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.security.SecureRandom
import java.security.cert.X509Certificate
import java.util.concurrent.TimeUnit
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager

/**
 * Created by dongdongzheng on 2018/2/11.
 */
class RetrofitManage {

    var retrofit: Retrofit? = null

    var userService: UserService? = null


    private object Instance {
        var retrofitManage = RetrofitManage()
    }

    companion object {
        val DEFAULT_TIMEOUT = 20000L

        fun get(): RetrofitManage {
            return Instance.retrofitManage
        }

    }

    init {
        Log.d("RetrofitManage", "RetrofitManage初始化------------------")


        var gson = GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").serializeNulls().create()
        retrofit = Retrofit.Builder()
                .client(getOkhttpClient())// okhttp的实现
                .addConverterFactory(GsonConverterFactory.create(gson))// Gson支持
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())// RxJava支持
                .baseUrl(BuildConfig.Base_Url)// 请求地址
                .build()

        userService = retrofit?.create(UserService::class.java)

    }

    fun getOkhttpClient(): OkHttpClient? {

        var builder = OkHttpClient.Builder()
        if (BuildConfig.DEBUG) {
            builder.addInterceptor(getHttpLoggin())
        }
//        builder.sslSocketFactory(createSSLSocketFactory())
        builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)
                .readTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)
                .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)
                .retryOnConnectionFailure(true)// 错误重连

        return builder.build()
    }

    fun getHttpLoggin(): HttpLoggingInterceptor {
        var loggingInterceptor = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger { message ->
            Log.d("RetrofitManage", "OkHttp: " + message)
        })
        loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
        return loggingInterceptor
    }


    private fun createSSLSocketFactory(): SSLSocketFactory? {
        var ssfFactory: SSLSocketFactory? = null

        try {
            val sc = SSLContext.getInstance("TLS")
            sc.init(null, arrayOf<TrustManager>(TrustAllCerts()), SecureRandom())

            ssfFactory = sc.socketFactory
        } catch (e: Exception) {
        }

        return ssfFactory
    }


    class TrustAllCerts : X509TrustManager {
        override fun checkClientTrusted(p0: Array<out X509Certificate>?, p1: String?) {
            //TODO("not implemented") //To change body of created functions use File | Settings |
            // File Templates.
        }

        override fun checkServerTrusted(p0: Array<out X509Certificate>?, p1: String?) {
            //TODO("not implemented") //To change body of created functions use File | Settings |
            // File Templates.
        }

        override fun getAcceptedIssuers(): Array<X509Certificate> {
            //TODO("not implemented") //To change body of created functions use File | Settings |
            // File Templates.

            return arrayOf(MyX509Certificate())
        }

    }


}